package com.jy.api.service.impl;

import com.jy.api.dao.StockOrderItemDao;
import com.jy.api.dao.StockOrderShopDao;
import com.jy.api.domain.OrderItem;
import com.jy.api.domain.StockOrder;
import com.jy.api.domain.StockOrderItem;
import com.jy.api.service.StockOrderShopService;
import com.jy.api.signUpReq.StockOrderShopReq;
import com.jy.api.signUpReq.StoreOrderSignUpReq;
import com.jy.api.util.Result;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xiaohua on 2019/4/20.
 */
@Service
public class StockOrderShopServiceImpl implements StockOrderShopService {
    @Autowired
    private StockOrderShopDao shopDao;

    @Override
    public Page<StockOrder> findAllByPage(String userName, Pageable pageable) {
        List<String> list = new ArrayList<>();
        list.add("PAY");
        list.add("UNPAY");
        if (StringUtils.equals(userName, "13980547109")) {
            return shopDao.findAllByStatusInAndEnabledOrderByAddTimeDesc(list,true, pageable);
        } else {
            return shopDao.findAllByStatusInAndOrderUserNameAndEnabledOrderByAddTimeDesc(list,userName,true,pageable);
        }
    }

    @Override
    @Transactional
    public void shopMerge(StockOrderShopReq req) {
        StockOrder order = shopDao.findOne(req.getId());
        if (StringUtils.equals(req.getUserName(), "13980547109")) {
            if (StringUtils.equals(req.getType(), "PAY")) {
                order.setPayEnabled(req.isPayEnabled());
            } else {
                order.setSendEnabled(req.isSendEnabled());
            }
        }
        shopDao.save(order);
    }

    @Override
    @Transactional
    public Map<String, Object> orderShop(StoreOrderSignUpReq req) {
        StockOrder order = new StockOrder(req);
        StockOrder save = shopDao.save(order);
        Map<String, Object> map = new HashMap<>();
        List<StockOrderItem> orderItems = new ArrayList<>();
        for (StoreOrderSignUpReq.Items re : req.getItems()) {
            StockOrderItem item = new StockOrderItem(re);
            orderItems.add(item);
        }
        save.setItems(orderItems);
        StockOrder or = shopDao.save(save);
        map.put("result", new Result(200, "下单成功"));
        map.put("data", or);
        return map;
    }
}
